package com.test.qnews.activity;


import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.test.qnews.Love;
import com.test.qnews.LoveDao;
import com.test.qnews.R;
import com.test.qnews.RecommendDao;
import com.test.qnews.adapter.CommonAdapter;
import com.test.qnews.db.DaoSingleton;
import java.util.List;

/**
 * Created by dllo on 16/1/23.
 */
public class LoveActivity extends BaseActivity {
    private CommonAdapter commonAdapter;
    private ListView listView;
    private LoveDao loveDao = DaoSingleton.getInstance().getLoveDao();


    @Override
    protected int setLayout() {
        return R.layout.fragment_recommend;
    }

    @Override
    protected void initView() {
        listView = (ListView) findViewById(R.id.lv_recommend);
        commonAdapter = new CommonAdapter(1,search(),this);
        listView.setAdapter(commonAdapter);
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                delData(position);
                Toast.makeText(LoveActivity.this, "已删除", Toast.LENGTH_SHORT).show();
                return false;
            }
        });


    }
    //db查询
    private List<Love> search() {
        if (loveDao != null) {
//            return loveDao.queryBuilder().orderDesc(LoveDao.Properties.Title).list();
            return loveDao.queryBuilder().list();
        } else {
            return null;
        }
    }

    /**
     * 删除收藏的数据并更新adapter
     * search().get(search().size()-position -1    倒序删除
     */
    private void delData(int position){
//        try{
             loveDao.deleteByKey(search().get(search().size()-position -1).getTitle());
//             search().remove(position);
//            commonAdapter.notifyDataSetChanged();
        commonAdapter = new CommonAdapter(1,search(),this);
        listView.setAdapter(commonAdapter);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }

}
